const AIChoiceTemp = `
返回格式如下：
<question>问题</question>
<choices>
    <choice>A.选项</choice>
    <choice>B.选项</choice>
    <choice>C.选项</choice>
    <choice>D.选项</choice>
</choices>
<Right>正确选项</Right>
`;

function changeChoiceQuestion(dataContent) {
    return (`
        题目：${dataContent.Body}\n
        选项：${JSON.stringify(dataContent.Choices)}\n
        答案：${dataContent.RightChoice}
    `)
}

/** Katex 格式化 */
function useKatex() {

    function getFormatConfig() {
        return {
            case: {
                regNS: '\\(\n\\begin{cases}',
                regNE: '\\end{cases}\n\\)',
                regRS: '\\(\\begin{cases}',
                regRE: '\\end{cases}\\)'
            },
            hasCase(inContent) {
                if (isEmpty(inContent)) return false;
                return inContent.indexOf(this.case.regNS) !== -1 || inContent.indexOf(this.case.regRS) !== -1
            },
            renderCase(inContent) {
                // console.log(`${this.case.regRS}${inContent.replace(/\n/g, '')}${this.case.regRE}`)
                return vmDomKatex(`${this.case.regRS}${inContent.replace(/\\neq/g, '_neq_').replace(/\n/g, '').replace(/_neq_/g, '\\neq')}${this.case.regRE}`);
            },
            align: {
                regNS: '\\[\n\\begin{align\*}',
                regNE: '\\end{align\*}\n\\]',
                regRS: '\\[\\begin{aligned}',
                regRE: '\\end{aligned}\\]'
            },
            hasAlign(inContent) {
                if (isEmpty(inContent)) return false;
                return inContent.indexOf(this.align.regNS) !== -1 || inContent.indexOf(this.align.regRS) !== -1
            },
            renderAlign(inContent) {
                // console.log('===============inContent', inContent)
                // console.log(`${this.align.regRS}${inContent.replace(/\n/g, '')}${this.align.regRE}`)
                return vmDomKatex(`${this.align.regRS}${inContent.replace(/\\neq/g, '_neq_').replace(/\n/g, '').replace(/_neq_/g, '\\neq')}${this.align.regRE}`);
            },
        }
    }

    function toKatexJson(inContent, type) {
        const config = getFormatConfig();
        const { regNS, regRS, regNE, regRE } = config[type];
        let tempContent = inContent.replace(/\\\[\n\\begin\{align\*\}/g, regRS);
        tempContent = tempContent.replace(new RegExp(regNS, 'g'), regRS);
        tempContent = tempContent.replace(/\\end{align\*}\n\\\]/g, regRE);
        tempContent = tempContent.replace(new RegExp(regNE, 'g'), regRE);

        let list = tempContent.split(regRS);
        const contentList = [];
        for (let i = 0; i < list.length; i++) {
            const item = list[i]
            // 常规文本
            if (i === 0) {
                contentList.push({
                    type: 'conventional',
                    text: item
                })
                continue;
            }

            const contentAndRight = item.split(regRE);
            if (contentAndRight.length > 1) {
                // 公式
                contentList.push({
                    type: type,
                    text: contentAndRight[0]
                });
                // 常规文本
                contentList.push({
                    type: 'conventional',
                    text: contentAndRight[1]
                });
            } else {
                // AI 智障了，推理未完成
                // 公式
                contentList.push({
                    type: type,
                    text: contentAndRight[0]
                });
            }
        }

        return contentList;
    }

    function formulaFormat(inContent) {
        const result = [];
        if (isEmpty(inContent)) return result;
        // console.log('formulaFormat inContent', inContent)
        const config = getFormatConfig();
        // console.log('config', config)

        if (isString(inContent)) {
            // console.log('config.hasAlign(inContent)', config.hasAlign(inContent))
            if (config.hasAlign(inContent)) {
                const list = toKatexJson(inContent, 'align');
                return [...result, ...formulaFormat(list)]
            }

            if (config.hasCase(inContent)) {
                const list = toKatexJson(inContent, 'case');
                return [...result, ...formulaFormat(list)]
            }

            return [{ type: 'conventional', text: inContent }]
        }

        // console.log('isArray(inContent)', Array.isArray(inContent))
        if (Array.isArray(inContent)) {

            inContent.forEach(item => {
                if (['case', 'align'].includes(item.type)) {
                    result.push(item);
                } else {
                    if (config.hasCase(item.text)) {
                        result = [...result, ...formulaFormat(item.text)]
                    } else if (config.hasAlign(item.text)) {
                        result = [...result, ...formulaFormat(item.text)]
                    } else {
                        result.push(item);
                    }
                }
            })

            return result;
        }

        return result;
    }

    /** 算式格式化 */
    function vmDomKatex(content = '') {
        const div = document.createElement('div')
        div.textContent = content;
        renderMathInElement(div, {
            delimiters: [
                { left: '$$', right: '$$' },
                { left: '$', right: '$' },
                { left: '\\(', right: '\\)' },
                { left: '\\[', right: '\\]' },
                { left: '\\begin{aligned}', right: '\\end{aligned}' },
                { left: '\\begin{cases}', right: '\\end{cases}' }
            ],
            throwOnError: false
        });
        return div.innerHTML;
    }

    /** 格式化算式 */
    function formatOLPExpressionArr(inContent = '') {
        if (isEmpty(inContent)) return inContent;
        // console.log('=========inContent', inContent)
        const list = formulaFormat(inContent);
        const config = getFormatConfig()

        // console.log('========== list', list)
        return list.reduce((prev, curr) => {
            if (curr.type === 'align') {
                // console.log('========align')
                return [...prev, config.renderAlign(curr.text)]
            }

            if (curr.type === 'case') {
                // console.log('========case')
                return [...prev, config.renderCase(curr.text)]
            }

            // console.log('curr.text', JSON.stringify(curr.text));
            return [...prev, vmDomKatex(curr.text)]
        }, []);
    }
    function formatOLPExpression(inContent = '') {
        if (isEmpty(inContent)) return inContent;
        return formatOLPExpressionArr(inContent).join('</br>');
    }

    /** 清理占位符 */
    function clearOLPPlace(inContent = '') {
        return inContent.replace(/灬灬/g, '');
    }

    function isJsonString(str) {
        try {
            JSON.parse(str);
            return true;
        } catch (e) {
            console.log('====str', str)
            console.log('====eeee', e)
            return false;
        }
    }

    function AIBackUnSerializeToChoiceQuestion(inContent = '') {
        const questionInfo = {
            question: '',
            options: [],
            loadedQuestion: 'start',
            loadedOptions: 'none'
        };

        if (inContent.includes('"question": "')) {
            const questionStrs = inContent.split('"question": "')
            if (inContent.includes('",')) {
                const questionStr = questionStrs[1].split('",')[0]
                const leftlength = questionStr.split('\(');
                const rightlength = questionStr.split('\)');
                // console.log('questionStr', questionStr)
                // console.log('leftlength.length', leftlength.length)
                // console.log('rightlength.length', rightlength.length)
                if (rightlength.length < leftlength.length) {
                    questionInfo.question = questionStr + '\\)'
                } else {
                    questionInfo.question = questionStr
                }

                questionInfo.loadedQuestion = 'end'

                if (inContent.includes('"options":')) {
                    questionInfo.loadedOptions = 'loading'
                }

                // console.log('isJsonString(inContent) before==', inContent.replace(/\\/g, '\\\\'))
                if (isJsonString(inContent.replace(/\\/g, '\\\\'))) {
                    const questionBack = JSON.parse(inContent.replace(/\\/g, '\\\\'))
                    // console.log('isJsonString(inContent)', true)
                    questionInfo.options = questionBack.options
                    // console.log('questionBack.options', JSON.stringify(questionBack.options))
                    questionInfo.loadedOptions = 'end'
                }
            } else {
                if (questionStrs.length > 1) {
                    questionInfo.loadedQuestion = 'loading'
                    questionInfo.question = questionStrs[1];
                }
            }
        }

        return questionInfo;
    }

    /**
     * 题目格式化
     * @param inContent 内容
     * @param questionType 题型
     * @returns 结构化的内容
     */
    function structureQuestion(inContent = '', questionType = '') {
        let tpConent = inContent.replace(/#/g, '灬灬');

        const questionJson = {};
        questionJson.question = formatOLPExpression(tpConent);
        // console.log('questionJson', JSON.stringify(questionJson))

        return questionJson;
    }

    function structureKnowledge(inContent) {
        let knowledge = [];
        if (inContent.includes('<knowledge>')) {
            const sp1 = inContent.split('<knowledge>');
            if (!inContent.includes('</knowledge>')) {
                const list = sp1[1].split('丨');
                knowledge = list.map(item => {
                    const kl = item.split('<=>');
                    return {
                        knowledge: kl[0],
                        rate: kl.length > 1 ? kl[1] : ''
                    };
                })
            } else {
                const list = sp1[1].split('</knowledge>')[0].split('丨');
                knowledge = list.map(item => {
                    const kl = item.split('<=>');
                    return {
                        knowledge: kl[0],
                        rate: kl.length > 1 ? kl[1] : ''
                    };
                })
            }
        }

        return knowledge;
    }

    function structureAnalysis(inContent, callback) {
        if (inContent.includes('<analysis>')) {
            const sp1 = inContent.split('<analysis>');
            if (!inContent.includes('</analysis>')) {
                return formatOLPExpression(sp1[1]);
            } else {
                callback && callback()
                return formatOLPExpression(sp1[1].split('</analysis>')[0]);
            }
        }

        if (inContent.length > '<analysis>'.length) {
            return inContent.split('<knowledge>')[0];
        }
        return ''
    }

    /**
     * AI解析或者咨询转JSON结构化
     * @param inContent 内容
     * @param elterenable 是否换行
     * @returns 结构化的内容
     */
    function structureAsk(inContent, elterenable = false) {
        // const content = inContent ? inContent : '';
        if (inContent.includes('question')) {
            return structureQuestion(inContent);
        }

        if (inContent.includes('knowledge')) {
            return structureKnowledge(inContent);
        }

        if (inContent.includes('analysis')) {
            return structureAnalysis(inContent);
        }

        // console.log('====structureAsk content', content);
        const info = formatOLPExpressionArr(clearOLPPlace(inContent));
        // console.log('formatOLPExpressionArr(clearOLPPlace(inContent))', JSON.stringify(info))
        if (elterenable && info) {
            return info.join('');
        }
        return info;
    }

    return {
        AIBackUnSerializeToChoiceQuestion,
        structureQuestion, structureAsk, vmDomKatex, clearOLPPlace, formatOLPExpression, structureKnowledge, structureAnalysis,
    }
}

const {
    AIBackUnSerializeToChoiceQuestion,
    structureQuestion, structureAsk, vmDomKatex, clearOLPPlace, formatOLPExpression, structureKnowledge, structureAnalysis } = useKatex();
